// ActionScript file
		
			
			import com.sodimac.util.commons.UploadPostHelper;
			import com.sodimac.v2s.view.components.ScreenFormat;
			import mx.events.DataGridEventReason;
			import com.sodimac.util.commons.DataGridExport;
			import com.sodimac.v2s.model.ComprasModelLocator;
			import mx.binding.utils.ChangeWatcher;
			import mx.events.CloseEvent;
			import mx.utils.StringUtil;
			import com.sodimac.v2s.events.grabarPedidoCorpEvent;
			import mx.controls.LinkButton;
			import mx.controls.AdvancedDataGrid;
			import com.sodimac.util.commons.UtilString;
			import mx.controls.DateField;
			import com.sodimac.util.alerts.alert;
			import com.sodimac.util.commons.EstadosBPM;
			import com.sodimac.util.commons.Resources;
			import com.sodimac.util.controls.adgFooter.FooterAdvancedDataGridColumn;
			import com.sodimac.v2s.vo.InfoSfpVO;
			import mx.events.CollectionEvent;
		    import mx.events.AdvancedDataGridEvent;
		    import mx.events.ItemClickEvent;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			import mx.collections.ArrayCollection;
	        import mx.controls.NumericStepper;
		    import mx.controls.ButtonLabelPlacement;
	
			import mx.collections.ItemResponder;
			import mx.collections.errors.ItemPendingError;
			import mx.controls.dataGridClasses.DataGridColumn;
		    	
		    
			/* datos de pantalla */    
			[Bindable] private var numericStepperFac:ClassFactory;
				  
			[Bindable] public var paisesArr:Array = new Array();
			[Bindable] public var paisesNacArr:Array = new Array();
			[Bindable] public var prodCorpData:ArrayCollection;	
			[Bindable] public var prodNacData:ArrayCollection;
			[Bindable] public var infoSfpVo:InfoSfpVO;	
			[Bindable] public var paisesNombres:XMLList;
			[Bindable] public var reporteURL: String;
			[Bindable] public var uploadDataURL: String;
			[Bindable] public var existePedido: String = "0";				
				
			[Bindable] public var pedidoCorpId: Number;
			[Bindable] public var empresaId: String; 
			
			[Bindable] public var prodNacCLData:ArrayCollection = new ArrayCollection();
			[Bindable] public var prodNacCOData:ArrayCollection = new ArrayCollection();
			[Bindable] public var prodNacPEData:ArrayCollection = new ArrayCollection();
			[Bindable] public var prodNacARData:ArrayCollection = new ArrayCollection();
			
			public var prodCorpUpdated:ArrayCollection = new ArrayCollection();
			public var prodNacUpdated:ArrayCollection = new ArrayCollection();
			public var paisesPartArray:Array = new Array("CL","CO","PE","AR");   //orden de los paises que pueden participar de una SFPC
			public var paisesCorreccion:Array = new Array();                //contiene los paises a modificar
			public var cwDataGridCorp:ChangeWatcher; 
			public var cwDataGridNac:ChangeWatcher;
			
			
			private function onInit():void
			{
				trace("____"+  this.name + " -->  onInit.");
			
				//Escuchar cambios en arreglos 
				cwDataGridCorp = ChangeWatcher.watch(ComprasModelLocator.getInstance(),'prodConjHomData',onProductosChange);
				cwDataGridNac  = ChangeWatcher.watch(ComprasModelLocator.getInstance(),'prodConjNacData',onProductosChangeNac);
			
			}
			
  			private function onProductosChange(e:Event):void
			{
			    trace("____"+  this.name + " -->  onProductosChange.");
				 
				var col:AdvancedDataGridColumn;
		        var cols:Array = dg_corp.columns;				 
				//ocultar pais
				if ((paisesArr)  && (paisesArr.length>0) )
				{
					//obtener pais
					var hidePaises:Array = new Array();
					hidePaises = paisesPartArray;
					for (var j:int=0;j<paisesArr.length;j++) 
					{
						var cod:String;
						cod = paisesArr[j];
						for (var k:int=0;k<paisesPartArray.length;k++)
						{
							if (paisesPartArray[k] == cod)
								hidePaises.splice(k,1);
						}
					} 
					trace("-------------------------");
					trace(hidePaises);
					for (j=0;j<hidePaises.length;j++) 
					{
						var name:String = UtilString.toLowerCase(hidePaises[j]);
	 					for (k=0;k<cols.length;k++)  
						{
							 if (String(cols[k].dataField).indexOf(name +"_") != -1)
							 {
							 	 var column:FooterAdvancedDataGridColumn = dg_corp.columns[k];
							 	 column.visible = false;
							 }  
						} 
					}
					
				} else {
				
					//hide all 
					for (j=0;j<paisesPartArray.length;j++) 
					{
						var name2:String = UtilString.toLowerCase(paisesPartArray[j]);
	 					for (k=0;k<cols.length;k++)  
						{
							 if (String(cols[k].dataField).indexOf(name2 +"_") != -1)
							 {
							 	 var column2:FooterAdvancedDataGridColumn = dg_corp.columns[k];
							 	 column2.visible = false;
							 }  
						} 
					}			
				
				}	
		  				    
			    cwDataGridCorp.unwatch();
			} 			
			
		
  			private function onProductosChangeNac(e:Event):void
			{
			    trace(" ____"+  this.name + " -->  onProductosChangeNac.");
	
			    //asign array for countries and visibility
			    if ((prodNacData)  && (paisesNacArr.length >0))
			    {
			    	trace("asignando arreglos por pais....");
			    
			    	for (var j:int=0;j<paisesNacArr.length;j++) 
			    	{
			    		var prefix:String = paisesNacArr[j];
			    		if (prefix == "CL")
			    		{
			    			prodNacCLData = prodNacData[j];
			    		} else if (prefix == "CO")
			    		{
			    			prodNacCOData = prodNacData[j];
			    		} else if (prefix == "PE")
			    		{
			    			prodNacPEData = prodNacData[j];
			    		}else if (prefix == "AR")
			    		{
			    			prodNacARData = prodNacData[j];
			    		} 
			    	} 
			    	
			    }				
				
				// hide countries compra individual
				if ((paisesNacArr)  && (paisesNacArr.length>0) )
				{
					
					//obtener pais
					var hidePaises:Array = new Array();
					hidePaises = paisesPartArray;
					for (j=0;j<paisesNacArr.length;j++) 
					{
						var cod:String;
						cod = paisesNacArr[j];
						for (var k:int=0;k<paisesPartArray.length;k++)
						{
							if (paisesPartArray[k] == cod)
								hidePaises.splice(k,1);
						}
					}
					trace("hide nac " +  hidePaises);
					
					for (k=0;k<hidePaises.length;k++) 
					{
			    		var prefijo:String = hidePaises[k];
			    		if (prefijo == "CL")
			    		{
			    			vboxCL.visible=false;
			    			vboxCL.height=5;
			    		} else if (prefijo == "CO")
			    		{
			    			vboxCO.visible=false;
			    			vboxCO.height=5;
			    		} else if (prefijo == "PE")
			    		{
			    			vboxPE.visible=false;
			    			vboxPE.height=5;
			    		} else if (prefijo == "AR")
			    		{
			    			vboxAR.visible=false;
			    			vboxAR.height=5;
			    		}
			    									
					}
				}
				/*
				else
				{
					//hide all nac
					for (k=0;k<paisesPartArray.length;k++) 
					{
			    		var prefijo:String = paisesPartArray[k];
			    		if (prefijo == "CL")
			    		{
			    			vboxCL.visible=false;
			    			vboxCL.height=5;
			    		} else if (prefijo == "CO")
			    		{
			    			vboxCO.visible=false;
			    			vboxCO.height=5;
			    		} else if (prefijo == "PE")
			    		{
			    			vboxPE.visible=false;
			    			vboxPE.height=5;
			    		} else if (prefijo == "AR")
			    		{
			    			vboxAR.visible=false;
			    			vboxAR.height=5;
			    		}
			    									
					}				
				
				}
				*/
				
				
				if (existePedido == "1")  
				{
					btnEnviar.enabled = false;
					btnGuardar.enabled = false;
				}							
		  				    
			    cwDataGridNac.unwatch();
			}		
		
		
			

			private function modificaTotalesConj(event:AdvancedDataGridEvent):void
			{
				 trace(" ____"+  this.name + " -->  modificaTotalesConj.");
				
				var cantidad:Number = NumericStepper(event.currentTarget.itemEditorInstance).value;
				var prefix:String   = dg_corp.columns[event.columnIndex].dataField;
				var subPrice:Number = 0;
				var subKgs:Number   = 0;
				var subCbm:Number   = 0;
				var total:Number    = 0;				
				
				prefix = prefix.substr(0,3);
				trace("prefijo : " + prefix); 
				subPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
				subKgs   = Number(prodCorpData[event.rowIndex]["unit_kgs"]);
				subCbm   = Number(prodCorpData[event.rowIndex]["unit_cbm"]);
				 
				 
				if (prefix == "sub")
				{
					
					//update totales all countries
					for (var j:int=0;j<paisesArr.length;j++) 
					{
						prefix = UtilString.toLowerCase(paisesArr[j]);
						if (!isNaN(prodCorpData[event.rowIndex][prefix + "_quantity"]))
						{
							cantidad =  Number(prodCorpData[event.rowIndex][prefix + "_quantity"]);
							
		 					prodCorpData[event.rowIndex][prefix + "_sub_price"] = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
							prodCorpData[event.rowIndex][prefix + "_sub_kgs"]   = (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
							prodCorpData[event.rowIndex][prefix + "_sub_cbm"]   = (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
							
							checkRequiereCorreccion(UtilString.toUpperCase(prefix), cantidad, event.rowIndex);							
							
						}
					}					
					
					
				} 
				else
				{ 
					//update subs
		 			prodCorpData[event.rowIndex][prefix + "sub_price"] = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
					prodCorpData[event.rowIndex][prefix + "sub_kgs"]   = (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
					prodCorpData[event.rowIndex][prefix + "sub_cbm"]   = (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
					
					//sum all countries
					for (var t:int=0;t<paisesArr.length;t++) 
					{
						prefix = UtilString.toLowerCase(paisesArr[t]);
						if (!isNaN(prodCorpData[event.rowIndex][prefix + "_quantity"]))
						{
							total +=  Number(prodCorpData[event.rowIndex][prefix + "_quantity"]);
						}
					}
					
					prodCorpData[event.rowIndex]["sub_quantity"] = (Number(total*100)/100);
					prodCorpData[event.rowIndex]["sub_total"] = (Number(total*subPrice*100)/100);
				}	
				 
			}
			
			
		
			private function validaCantidad(event:AdvancedDataGridEvent):void
			{
				var newValor:Number = NumericStepper(event.currentTarget.itemEditorInstance).value;
				var oldValor:Number = event.currentTarget.editedItemRenderer.data[event.dataField];
				var caseName:String = event.dataField;
				var prefix:String = caseName.substr(0,3);
				var pais:String = UtilString.toUpperCase(prefix.substr(0,2));
				var prefijo_pais:String = "";
				var casePack:Number = 0; 
				var resto:Number = 0;
				var row:Number = 0; 
				var qty:Number = 0;
				var subQty:Number = 0;
				var newQty:Number = 0;
				var sumVendor:Number = 0;
				var proposed:Boolean= false;
				var unitPrice:Number = 0;				
				
				
                if ( (newValor == oldValor)  || (event.reason == DataGridEventReason.CANCELLED)) {
                    return; 
                }
                
				if (oldValor != -1)
				{

					subQty =  oldValor;
					if ( prefix == "sub" )
					{
						//distribuir diferencia
						trace("editando Sub Quantity ...");
						if ( (paisesArr) && (paisesArr.length) && (subQty > 0) ) {
		
								//calculo mayor  y menor
								for (var k:int=0; k < paisesArr.length;k++)
								{
									qty = 0;
									casePack = 0;
									resto = 0;
									newQty = 0;
									
									prefijo_pais = UtilString.toLowerCase(paisesArr[k]) + "_";
									casePack = Number(prodCorpData[event.rowIndex][prefijo_pais + "case_pack"]);
									qty =  Number(prodCorpData[event.rowIndex][prefijo_pais + "quantity"]);
								
									if ( (qty) && paisesArr[k] == "CL"){
										
										newQty = Math.round( (newValor* ((qty*100/subQty)/100)) );
										resto = newQty%casePack;
										if ( resto != 0)
										{
											proposed= true;
											newQty = Math.ceil(newQty/casePack)*casePack;
										}
										sumVendor += (newQty);
										prodCorpData[event.rowIndex]["cl_quantity"] = (newQty);
									
						    		} else if ( (qty) && paisesArr[k]  == "CO"){
			
										newQty =  Math.round( (newValor* ((qty*100/subQty)/100)) );
										resto = newQty%casePack;
										if ( resto != 0)
										{
											proposed= true;
											newQty = Math.ceil(newQty/casePack)*casePack;
										}
										sumVendor += (newQty);
										prodCorpData[event.rowIndex]["co_quantity"] = ( newQty);			    			
						    			
						    		} else if ((qty) && paisesArr[k]  == "PE"){
										newQty =  Math.round( (newValor* ((qty*100/subQty)/100)) );
										resto = newQty%casePack;
										if ( resto != 0)
										{
											proposed= true;
											newQty = Math.ceil(newQty/casePack)*casePack;
										}
										sumVendor += (newQty);
										prodCorpData[event.rowIndex]["pe_quantity"] = (newQty);			    			
						    			
						    		} else if ((qty) && paisesArr[k]  == "AR"){
										newQty =  Math.round( (newValor* ((qty*100/subQty)/100)) );
										resto = newQty%casePack;
										if ( resto != 0)
										{
											proposed= true;
											newQty = Math.ceil(newQty/casePack)*casePack;
										}
										sumVendor += (newQty);
										prodCorpData[event.rowIndex]["ar_quantity"] = ( newQty);		    			
						    			
						    		}
						    		
								}
							
								
							
							//update col sub_total = qty * unit_price
							unitPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
							prodCorpData[event.rowIndex]["sub_total"]  = Number(sumVendor * unitPrice);
							
							NumericStepper(event.currentTarget.itemEditorInstance).value = sumVendor;
							event.currentTarget.editedItemRenderer.data[event.dataField] = -1;
							if (proposed)
							{
								alert.info("Se propone una cantidad superior a la ingresada, la cual ha sido distribuída entre los países participantes.");
							} else {
								alert.info("La cantidad ingresada ha sido distribuída entre los países participantes.");
							}
														
		
						} else if (subQty  == 0)
						{
							sumVendor = newValor;
							prodCorpData[event.rowIndex][ UtilString.toLowerCase(paisesArr[0]) + "_quantity"]  = newValor;					
							
							//update col sub_total = qty * unit_price
							unitPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
							prodCorpData[event.rowIndex]["sub_total"]  = Number(sumVendor * unitPrice);
							
							event.currentTarget.editedItemRenderer.data[event.dataField] = -1;						
						
						}					
						
	
					} 
					else
					{
					
						//define case-pack related
						caseName = prefix + "case_pack";
						casePack = Number(prodCorpData[event.rowIndex][caseName]);
						
		
						if ( isNaN(casePack) || (casePack ==0)) 
						{
							AdvancedDataGrid(event.currentTarget).destroyItemEditor();
							event.preventDefault();
							alert.error("Case Pack no válido, no es posible validar cantidad  ingresada.");
						} 
						else 
						{
							
							var max:Number = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
							if (newValor == max)
							{
								AdvancedDataGrid(event.currentTarget).destroyItemEditor();
								event.preventDefault();								
								alert.warning("Valor ingresado es igual o superior al máximo permitido ("+ pesosFmt.format(max) +").");
							}
							else
							{						
							
								resto=newValor%casePack;
								if (resto !=0)
								{
									newValor = 	Math.ceil(newValor/casePack)*casePack;
									NumericStepper(event.currentTarget.itemEditorInstance).value = 	newValor;
									event.currentTarget.editedItemRenderer.data[event.dataField] = -1;			
									alert.warning("La cantidad ingresada debe ser múltiplo del case pack ("+ casePack + ").  Se propone una cantidad superior válida.");
								}
								
								//siempre validar si requiere correcion 
								checkRequiereCorreccion(pais, newValor, event.rowIndex);

/* 2010-01-28 - Modificado por RGA  (Corrige problema al chequear correción)
								else 
								{
									
									//si cambio es mayor que la tolerancia, habilitar label "Requiere Correccion"
									checkRequiereCorreccion(pais, newValor, event.rowIndex);
	
								}
*/
							}	
						}
					}
					
				}
			}


	        private function checkRequiereCorreccion(pais:String, newValor:Number, row:Number):void 
	        {
				var valorTol:Number = 0;
				var valorQty:Number = 0;
				var prefix:String = UtilString.toLowerCase(pais) + "_";
				var encendido:Boolean = false;
				
				valorTol = prodCorpData[row][prefix + "max_tolerancia"];
				
				if (newValor > valorTol)						
				{
						if (pais == "CL")
						{
							cl_group.headerText = "on";
						}
						else if (pais == "CO")
						{
							co_group.headerText = "on";
						}						
						else if (pais == "PE")
						{
							pe_group.headerText = "on";
						}
						else if (pais == "AR")
						{
							ar_group.headerText = "on";
						}
					
					//inserta en arreglo	
					if (paisesCorreccion.indexOf(pais) < 0)
					{
						paisesCorreccion.push(pais);
					}
					
					//(cambio RG 19.10.2009)  
					//En caso mostrar "Requiere Confirmación" se debe bloquear boton guardar 
					btnGuardar.enabled = false;						
					
		        }
		        else
		        {
					//verifico si corresponde mantener encendido label
					encendido = false;		        
		        	for (var j:int=0;j<prodCorpData.length;j++) 
					{
						if (j != row)
						{
							valorTol = isNaN(prodCorpData[j][prefix + "max_tolerancia"])? 0: Number(prodCorpData[j][prefix + "max_tolerancia"]);
							valorQty = isNaN(prodCorpData[j][prefix + "quantity"])? 0: Number(prodCorpData[j][prefix + "quantity"]);
							
							if (valorQty > valorTol)
							{
								encendido = true;
								break;
							}
						} 
					}
					
					if (!encendido)
					{
						if (pais == "CL")
						{
							cl_group.headerText = "off";
						}
						else if (pais == "CO")
						{
							co_group.headerText = "off";
						}						
						else if (pais == "PE")
						{
							pe_group.headerText = "off";
						}
						else if (pais == "AR")
						{
							ar_group.headerText = "off";
						}

						
						//remove form array	
						for (var k:int=0;k<paisesCorreccion.length;k++)
						{
							if (paisesCorreccion[k] == pais)
								paisesCorreccion.splice(k,1);
						}							
							
					} 		        
		        
	        	}
	        	
	        	if (paisesCorreccion.length == 0)
	        	{
	        		btnGuardar.enabled = true;
	        	}
	        }

			
			
			
	        private function onCreationCompleteDGCorp():void 
	        {
				var col:AdvancedDataGridColumn;
		        var cols:Array = dg_corp.columns;
				
				numericStepperFac = new ClassFactory(NumericStepper);
		        numericStepperFac.properties = {minimum:0, maximum:999999999, maxChars:9};
		        
				trace("____"+  this.name + " -->  onCreationCompleteDGCorp.");
		        
		        var i:int =0;    
		        while (i < cols.length)
		        {
		            	//para todas las columnas
		            	col= cols[i];
		            	col.editable = false;
		            	col.headerWordWrap = true;
							            	
		            	//renderiza NumericStepper
		            	if ((i==7) || (i==12)  || (i==20) || (i==28) || (i==36)) 
		            	{
			            	col.editable = true;
			            	col.editorDataField = "value";
			            	col.itemEditor = numericStepperFac;
		            	}
		            	
						//format
						if ( (i==6) ||(i==8) || ((i>=14) && (i<=16)) || ((i>=22) && (i<=24)) || ((i>=30) && (i<=32)) || ((i>=38) && (i<=40)) ) 
						{
							var sf_c8:ClassFactory = new ClassFactory(ScreenFormat);
							sf_c8.properties = {fieldName:  col.dataField}
							col.itemRenderer = sf_c8; 
						}		            	
		            	
		            	i++;
		        }
		        
	         }
	         
	         
			private function modificaTotalesNac(event:AdvancedDataGridEvent, paisArr:ArrayCollection):void
			{
				var cantidad:Number =  paisArr.getItemAt(event.rowIndex).paisQuantity;
				var subPrice:Number = 0;
				var subKgs:Number   = 0;
				var subCbm:Number   = 0;
				var total:Number    = 0;
				
				subPrice = Number(paisArr[event.rowIndex]["unitPrice"]);
				subKgs   = Number(paisArr[event.rowIndex]["unitKgs"]);
				subCbm   = Number(paisArr[event.rowIndex]["unitCbm"]);

				// Get the name of the column being editted.
				paisArr.getItemAt(event.rowIndex).subPrice = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
				paisArr.getItemAt(event.rowIndex).subKgs =   (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
				paisArr.getItemAt(event.rowIndex).subCbm =   (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
				
			} 	         

			private function validaCantidadNac(event:AdvancedDataGridEvent, dataArr:ArrayCollection, pais:String):void
			{
				var newValor:Number = NumericStepper(event.currentTarget.itemEditorInstance).value;
				var oldValor:Number = event.currentTarget.editedItemRenderer.data[event.dataField];
				var casePack:Number = dataArr.getItemAt(event.rowIndex).casePack; 
				var resto:Number    = 0;
				
				
				if (oldValor != -1)
				{
					if ( isNaN(casePack) || (casePack ==0)) 
					{
						AdvancedDataGrid(event.currentTarget).destroyItemEditor();
						event.preventDefault();
						alert.error("Case Pack no válido, no es posible validar cantidad  ingresada.");
					} 
					else 
					{
						var max:Number = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
						if (newValor == max)
						{
							AdvancedDataGrid(event.currentTarget).destroyItemEditor();
							event.preventDefault();	
							alert.warning("Valor ingresado es igual o superior al máximo permitido ("+ pesosFmt.format(max) +").");
						}
						else
						{					
							resto=newValor%casePack;
							if (resto !=0)
							{
								NumericStepper(event.currentTarget.itemEditorInstance).value = Math.ceil(newValor/casePack)*casePack;
								event.currentTarget.editedItemRenderer.data[event.dataField] = -1;
								alert.warning("La cantidad ingresada debe ser múltiplo del case pack ("+ casePack + "). Se propone una cantidad superior válida.");
							} 
	
						}	
					}
				}	

			}

 				private function onCreationCompleteDGNac(adg:AdvancedDataGrid):void {
					var i:int = 0;
					var col:AdvancedDataGridColumn;
					var cols:Array = adg.columns;
					var anchoCols:Array = new Array(.06,.06,.2,.06,.08,.08,
													.08,.06,.08,.08,.08,.08);
					
					trace("____"+  this.name + " -->  onCreationCompleteDGNac");
					numericStepperFac = new ClassFactory(NumericStepper);
					numericStepperFac.properties = {minimum:0, maximum:999999999, maxChars:9};
					
					while (i < cols.length)
					{
						//para todos
						col= cols[i];
						col.editable = false;
						col.width = Math.round(adg.width*anchoCols[i]);

						//renderiza NumericStepper
						if (i==8)
						{
							col.editable = true;
							col.editorDataField = "value";
							col.itemEditor = numericStepperFac;
						}
						//format
						if (i==6)
						{
							var sf_n6:ClassFactory = new ClassFactory(ScreenFormat);
							sf_n6.properties = {fieldName:  col.dataField}
							col.itemRenderer = sf_n6; 
						}		
						if (i>8)
						{
							var sf_n8:ClassFactory = new ClassFactory(ScreenFormat);
							sf_n8.properties = {fieldName:  col.dataField}
							col.itemRenderer = sf_n8; 
						}
						i++;
					}
				} 


	         
	        public function textFunction(col:AdvancedDataGridColumn):String
			{
				var txt:String = "";
				if ((col.headerText =="Case Pack") || (col.headerText =="CP"))
				{
					txt="Total";
				}
				return txt;
			}
			
			
			public function sumFunctionCorp(col:AdvancedDataGridColumn):String
			{
				var sum:Number = 0;
				if (prodCorpData != null)
				{
					for (var i:int = 0; i < prodCorpData.length; i++)
					{
						if (!isNaN(prodCorpData[i][col.dataField]))
						{
							sum += Number(prodCorpData[i][col.dataField]);
						}
					}
				}
				return  pesosFmt.format((Number(sum*100)/100));
			}
			
			public function sumFunctionNacCL(col:AdvancedDataGridColumn):String
			{
				var sum:Number = 0;
				if (prodNacCLData != null)
				{
					for (var i:int = 0; i < prodNacCLData.length; i++)
					{
						if (!isNaN(prodNacCLData[i][col.dataField]))
						{
							sum += Number(prodNacCLData[i][col.dataField]);
						}
					}
				}
				return  pesosFmt.format((Number(sum*100)/100));
			}
			
			public function sumFunctionNacCO(col:AdvancedDataGridColumn):String
			{
				var sum:Number = 0;
				if (prodNacCOData != null)
				{
					for (var i:int = 0; i < prodNacCOData.length; i++)
					{
						if (!isNaN(prodNacCOData[i][col.dataField]))
						{
							sum += Number(prodNacCOData[i][col.dataField]);
						}
					}
				}
				return  pesosFmt.format((Number(sum*100)/100));
			}
			
			public function sumFunctionNacPE(col:AdvancedDataGridColumn):String
			{
				var sum:Number = 0;
				if (prodNacPEData != null)
				{
					for (var i:int = 0; i < prodNacPEData.length; i++)
					{
						if (!isNaN(prodNacPEData[i][col.dataField]))
						{
							sum += Number(prodNacPEData[i][col.dataField]);
						}
					}
				}
				return  pesosFmt.format((Number(sum*100)/100));
			}
			
			public function sumFunctionNacAR(col:AdvancedDataGridColumn):String
			{
				var sum:Number = 0;
				if (prodNacARData != null)
				{
					for (var i:int = 0; i < prodNacARData.length; i++)
					{
						if (!isNaN(prodNacARData[i][col.dataField]))
						{
							sum += Number(prodNacARData[i][col.dataField]);
						}
					}
				}
				return  pesosFmt.format((Number(sum*100)/100));
			}
			
			
			
			//styleFunction="setColorStyle" (for ADG)
	         public function setColorSubQuantity(data:Object, col:AdvancedDataGridColumn):Object
	         {
	             if(data["subQuantity"] <= 0)
	                 return {color:0xFF0000};
	             else    
	 				return {color:0x0000FF};
	 
	             return null;
	         }  		
	
	         public function setColorPaisQuantity(data:Object, col:AdvancedDataGridColumn):Object
	         {
	             if(data["paisQuantity"] <= 0)
	                 return {color:0xFF0000};
	             else    
	 				return {color:0x0000FF};
	 
	             return null;
	         } 	
	         




			private function getProductosModificados():void
			{
				//var productos:ArrayCollection = prodPicArr; 
				var version:String = infoSfpVo.version;
				var newValor:Number = 0;
				var oriValor:Number = 0; 

				//envio parcial o todo según version coorporativa
				if (version == "1.0")
				{
					//get all productos corp
					for (var i:int = 0; i < prodCorpData.length; i++)
					{
							var objProd:Object = new Object();
							objProd.vin = prodCorpData[i]["vin"];
							objProd.sub_quantity = prodCorpData[i]["sub_quantity"];
							
							var paises:Array = new Array();
							for (var q:int = 0; q < paisesArr.length; q++)
							{
								var prefix:String =  UtilString.toLowerCase(paisesArr[q]) + "_";
								if (!isNaN(prodCorpData[i][prefix + "quantity"]))
								{
									var prod:Object = new Object();
									prod.pais = UtilString.toUpperCase(prefix.substr(0,2));
									prod.sku = prodCorpData[i][prefix + "sku"];
									prod.cantidad = prodCorpData[i][prefix + "quantity"];
									paises.push(prod);
								}
								
							}
							objProd.paises = paises;
							prodCorpUpdated.addItem(objProd);

					}
					
					
				}				
				else
				{

					//get productos corp updated
					for (var t:int = 0; t < prodCorpData.length; t++)
					{
						newValor = prodCorpData[t]["sub_quantity"];
						oriValor = prodCorpData[t]["sub_quantity_original"];
						
						if ( newValor != oriValor )
						{
							var objOC:Object = new Object();
							objOC.vin = prodCorpData[t]["vin"];
							objOC.sub_quantity = newValor;
							
							var paises2:Array = new Array();
							for (var r:int = 0; r < paisesArr.length; r++)
							{
								var pref:String =  UtilString.toLowerCase(paisesArr[r]) + "_";
								if (!isNaN(prodCorpData[t][pref + "quantity"]))
								{
									var prod2:Object = new Object();
									prod2.pais = UtilString.toUpperCase(pref.substr(0,2));
									prod2.sku = prodCorpData[t][pref + "sku"];
									prod2.cantidad = prodCorpData[t][pref + "quantity"];
									paises2.push(prod2);
								}
								
							}
							objOC.paises = paises2;
							prodCorpUpdated.addItem(objOC);

				  		}
				  		
					}
				}	
					
					//get prod individuales modificados

					//get productos CL
					for (i=0; i < prodNacCLData.length; i++)
					{
						newValor = prodNacCLData[i]["paisQuantity"];
						oriValor = prodNacCLData[i]["paisQuantityOriginal"];					
						if ( newValor != oriValor )
						{
							var obj:Object = new Object();
							obj.idPais = "CL";
							obj.sku = prodNacCLData[i]["sku"];
				    		obj.cantInicial = newValor; 
				    		prodNacUpdated.addItem(obj);						
						}
					}				
					
					//get productos CO
					for (i=0; i < prodNacCOData.length; i++)
					{
						newValor = prodNacCOData[i]["paisQuantity"];
						oriValor = prodNacCOData[i]["paisQuantityOriginal"];					
						if ( newValor != oriValor )
						{
							var objProd2:Object = new Object();
							objProd2.idPais = "CO";
							objProd2.sku = prodNacCOData[i]["sku"];
				    		objProd2.cantInicial = newValor; 
				    		prodNacUpdated.addItem(objProd2);						
						}
					}			
				
					//get productos PE
					for (i=0; i < prodNacPEData.length; i++)
					{
						newValor = prodNacPEData[i]["paisQuantity"];
						oriValor = prodNacPEData[i]["paisQuantityOriginal"];					
						if ( newValor != oriValor )
						{
							var objProd3:Object = new Object();
							objProd3.idPais = "PE";
							objProd3.sku = prodNacPEData[i]["sku"];
				    		objProd3.cantInicial = newValor; 
				    		prodNacUpdated.addItem(objProd3);						
						}
					}				
		
					//get productos AR
					for (i=0; i < prodNacARData.length; i++)
					{
						newValor = prodNacARData[i]["paisQuantity"];
						oriValor = prodNacARData[i]["paisQuantityOriginal"];					
						if ( newValor != oriValor )
						{
							var objProd4:Object = new Object();
							objProd4.idPais = "AR";
							objProd4.sku = prodNacARData[i]["sku"];
				    		objProd4.cantInicial = newValor; 
				    		prodNacUpdated.addItem(objProd4);						
						}
					}	

				
			}		
				

				
			private function checkPaisesCorreccionEnviar():void 
			{

				if (paisesCorreccion.length > 0 )
				{

					//show msg paises participantes
					var lista:String = "";
					for (var i:int=0; i<paisesCorreccion.length; i++)
					{
						lista +=  XML(paisesNombres).pais.(@codIata == paisesCorreccion[i]).@nombre + "\n";
					}
					
					alert.info("Se enviará una solicitud de corrección a los siguientes paises:\n" + lista, onClickBtnEnviar);
				} else {
				
					onClickBtnEnviar(new CloseEvent("cerrar"));
				}

				
			}				

			public function onClickBtnEnviar(eventObj:CloseEvent):void
			{	
				var savePedidoEvt:grabarPedidoCorpEvent = new grabarPedidoCorpEvent();
				var version:Number = new Number(infoSfpVo.version);
				
				trace(" ____"+  this.name + " -->  onClickBtnEnviar.");
				
				//obtener productos modificados
				getProductosModificados();
				
	 			savePedidoEvt.idPedidoCorp = pedidoCorpId;
				savePedidoEvt.idEmpresa = empresaId;
				savePedidoEvt.idProveedor = infoSfpVo.proveedorId;
				savePedidoEvt.version = ((version - Math.floor(version))>0)? Math.ceil(version) + ".0":(version+1) + ".0";
				
				if (paisesCorreccion.length > 0 )
				{
					savePedidoEvt.estado = EstadosBPM.CORREGIR;
				} 
				else
				{
					savePedidoEvt.estado = EstadosBPM.ENVIO;
				}				
				
				if (prodCorpUpdated.length > 0 ) 
				{
					savePedidoEvt.productosCorpArr = prodCorpUpdated;  //listado de prod. modificados
				}	
				
				if (prodNacUpdated.length > 0 )
				{
					savePedidoEvt.productosNacArr = prodNacUpdated;  //listado de prod. modificados
				}	
				
				if (paisesCorreccion.length > 0 )
				{
					savePedidoEvt.paisesCorreccionArr = paisesCorreccion;  //listado de paises con solic correccion
				}				
				savePedidoEvt.dispatch();
				btnEnviar.enabled = false;
		      	btnGuardar.enabled = false;
											
			}

	         
			public function onClickBtnGuardar():void
			{	
				var savePedidoEvt:grabarPedidoCorpEvent = new grabarPedidoCorpEvent();
				var new_version:Number = new Number(infoSfpVo.version);
				
				//obtener productos modificados
				getProductosModificados();
				
				new_version += Number(0.1);
	 			savePedidoEvt.idPedidoCorp = pedidoCorpId;
				savePedidoEvt.idEmpresa = empresaId;
				savePedidoEvt.idProveedor = infoSfpVo.proveedorId;
				savePedidoEvt.estado = EstadosBPM.GUARDA;
				savePedidoEvt.version = new_version.toFixed(1);
	
				if (prodCorpUpdated.length > 0 ) 
				{
					savePedidoEvt.productosCorpArr = prodCorpUpdated;  //listado de prod. modificados
				}	
				
				if (prodNacUpdated.length > 0 )
				{
					savePedidoEvt.productosNacArr = prodNacUpdated;  //listado de prod. modificados
				}	
				
				savePedidoEvt.dispatch();
				btnGuardar.enabled = false;	
		      	btnEnviar.enabled = false;											
			}
			
			
			
			
		        private function generarReporte(formato:String):void 
		        {
		            
		            var url:String;
		            var sourceCorp:String =""; 
		            var sourceNac:String = "";
		            
		            if (dg_corp) {
		            	sourceCorp = DataGridExport.exportCSV(dg_corp, "Corporativos");
		            }
		            if (paisesNacArr) {
		            	
		            	for (var k:int=0;k<paisesNacArr.length;k++)
						{
				    		var prefijo:String = paisesNacArr[k];
							//trace("pais envio: " + prefijo);
				    		if (prefijo == "CL")
				    		{
				    			sourceNac  += DataGridExport.exportCSV(dg_cl, "CHILE") + "|";
				    		} else if (prefijo == "CO")
				    		{
				    			sourceNac  += DataGridExport.exportCSV(dg_co, "COLOMBIA") + "|";
				    		} else if (prefijo == "PE")
				    		{
				    			sourceNac  += DataGridExport.exportCSV(dg_pe, "PERU") + "|";
				    		} else if (prefijo == "AR")
				    		{
				    			sourceNac  += DataGridExport.exportCSV(dg_ar, "ARGENTINA") + "|";
				    		}
						}

		            		
		            }
		            
		            //remove last separator
		            if (sourceNac.charAt(sourceNac.length-1) == '|')
		            {
		            	sourceNac = sourceNac.substring(0, sourceNac.length-1);
		            }	
					
					//send data for report
					UploadPostHelper.uploadDataReport( 'ig7.txt', uploadDataURL, sourceCorp);
					UploadPostHelper.uploadDataReport( 'sub_ig7.txt', uploadDataURL, sourceNac);

					
				    //call report					
//					var variables:URLVariables = new URLVariables();
//					variables.pNumeroSFP = infoSfpVo.numeroSFP;
//					variables.pEstado = infoSfpVo.estado; 
//					variables.pFecha = infoSfpVo.fecha_formato;
//					variables.pProveedor = infoSfpVo.proveedorNombre + '  ( ' + infoSfpVo.proveedorId + ' )';
//					variables.pVersion = infoSfpVo.version;
//					variables.pIntMerchant = infoSfpVo.merchantNombre; 
//					variables.formato = formato;
//					variables.fileName ='ig7.txt';			            
					
		            var request:URLRequest = new URLRequest();
					request.url = reporteURL + "?formato="+ formato +
								"&fileName=ig7.txt"+
								"&pNumeroSFP="+ infoSfpVo.numeroSFP +
								"&pEstado="+ infoSfpVo.estado + 
								"&pFecha="+ infoSfpVo.fecha_formato +
								"&pProveedor="+ infoSfpVo.proveedorNombre + " ( " + infoSfpVo.proveedorId + " )" +
								"&pVersion="+ infoSfpVo.version +
								"&pIntMerchant="+ infoSfpVo.merchantNombre;
					request.method = URLRequestMethod.POST;
					//request.data = variables;
		            navigateToURL(request, '_blank');						
					

					
		        }						
	      			
	      		